package com.dragon.modules.yuegou.utils;

import com.dragon.modules.yuegou.model.merchant.Merchant;
import com.dragon.modules.yuegou.model.product.JdProductShare;
import com.dragon.modules.yuegou.model.product.PosterAppInfo;
import com.dragon.modules.yuegou.model.product.Sku;
import com.dragon.modules.yuegou.model.product.Spu;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.AttributedString;

/**
 * 生成海报工具类
 * 
 * @author 01
 *
 */
public class PostersUtils {

	private final Logger logger = LoggerFactory.getLogger(PostersUtils.class);

	private final String APP_DEFAULT_HEADIMG = "https://zzdhyzx.oss-cn-shenzhen.aliyuncs.com/crm-wx/poster-yzx/poster-yzx-default_member.png";

	public ByteArrayInputStream getJdSkuSharePosters(byte[] qRCodeBytes, JdProductShare sku, PosterAppInfo info) {
		try {
			BufferedImage image = new BufferedImage(info.getPostWidth(), info.getPostHeight(),
					BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = image.createGraphics();
			image = g.getDeviceConfiguration().createCompatibleImage(info.getPostWidth(), info.getPostHeight(),
					Transparency.TRANSLUCENT);
			g.dispose();
			g = image.createGraphics();

			g.fillRoundRect(0, 0, info.getPostWidth(), info.getPostHeight(), 0, 0);

			// 商品主图
			InputStream frameInputStream = getImageStream(sku.getShareImg());
			BufferedImage imageFrame = readImageIo(frameInputStream);
			g.drawImage(imageFrame.getScaledInstance(360, 360, Image.SCALE_SMOOTH), 15, 15, null);

			// 标题
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
			g.setFont(new Font("微软雅黑", Font.BOLD, 17));// 设置字体
			g.setColor(new Color(51, 51, 51));// 设置颜色
			String title = sku.getTitle();
			if (sku.getTitle().length() > 15)
				title = title.substring(0, 15) + "......";
			g.drawString(title, 15, 405);

			// 商品价格
			g.setFont(new Font("微软雅黑", Font.BOLD, 17));// 设置字体
			g.setColor(new Color(252, 67, 42));// 设置颜色
			g.drawString("¥ " + sku.getPrice(), 15, 435);

			// 京东价
			if (null != sku.getJdPrice()){
				g.setColor(new Color(163, 163, 163));// 设置颜色
				AttributedString as = new AttributedString("¥ " + sku.getJdPrice());
				as.addAttribute(TextAttribute.FONT, new Font("微软细黑", Font.PLAIN, 15));
				as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
				g.drawString(as.getIterator(), 105, 435);
			}

			ByteArrayInputStream bais = new ByteArrayInputStream(qRCodeBytes);
			logger.debug("转换流结束,bais={}", bais);
			BufferedImage imageCode = readImageIo(bais);
			g.drawImage(imageCode.getScaledInstance(100, 100, Image.SCALE_SMOOTH), 278, 385, null);

			// 上传合成图片至阿里云OSS
			byte[] resultImageBytes = imageToBytes(image, "png");
			ByteArrayInputStream resultImageInputStream = new ByteArrayInputStream(resultImageBytes);
			return resultImageInputStream;
		} catch (Exception e) {
			logger.error("getSkuSharePosters", e);
		}
		return null;
	}

	public ByteArrayInputStream getSkuSharePosters(byte[] qRCodeBytes, Sku sku, PosterAppInfo info, String headImgUrl) {
		try {
			BufferedImage image = new BufferedImage(info.getPostWidth(), info.getPostHeight(),
					BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = image.createGraphics();
			image = g.getDeviceConfiguration().createCompatibleImage(info.getPostWidth(), info.getPostHeight(),
					Transparency.TRANSLUCENT);
			g.dispose();
			g = image.createGraphics();

			g.setColor(new Color(255, 255, 255));
			g.fillRoundRect(0, 0, info.getPostWidth(), info.getPostHeight(), 10, 10);
			g.setColor(new Color(210, 210, 210));
			g.drawRect(20, 20, info.getPostWidth() - 40, info.getPostHeight() - 40);

			// 商品主图
			InputStream frameInputStream = getImageStream(sku.getMainImages());
			BufferedImage imageFrame = readImageIo(frameInputStream);
			g.drawImage(imageFrame.getScaledInstance(498, 300, Image.SCALE_SMOOTH), 30, 30, null);

			// 标题
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
			g.setFont(new Font("微软雅黑", Font.BOLD, 28));// 设置字体
			g.setColor(new Color(51, 51, 51));// 设置颜色
			String title = sku.getTitle();
			if (sku.getTitle().length() > 15)
				title = title.substring(0, 15) + "......";
			g.drawString(title, 50, 400);

			// 促销价
			g.setFont(new Font("微软雅黑", Font.BOLD, 24));// 设置字体
			g.setColor(new Color(252, 67, 42));// 设置颜色
			g.drawString("¥ " + sku.getDiscountPrice(), 50, 440);

			// 原价
			g.setColor(new Color(163, 163, 163));// 设置颜色
			AttributedString as = new AttributedString("¥ " + sku.getPrice());
			as.addAttribute(TextAttribute.FONT, new Font("微软细黑", Font.PLAIN, 24));
			as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
			g.drawString(as.getIterator(), 180, 440);

			// 微信图像
			if (StringUtils.isBlank(headImgUrl) || headImgUrl.equals("undefined"))
				headImgUrl = APP_DEFAULT_HEADIMG;
			InputStream inputStreamHead = getImageStream(headImgUrl);
			BufferedImage bufferedImageHead = readImageIo(inputStreamHead);
			BufferedImage circleBufferedImage = roundImage(bufferedImageHead, bufferedImageHead.getWidth(),
					bufferedImageHead.getWidth());
			g.drawImage(circleBufferedImage.getScaledInstance(90, 90, Image.SCALE_SMOOTH), 50, 500, null);

			// 向你推荐
			g.setFont(new Font("微软雅黑", Font.PLAIN, 28));// 设置字体
			g.setColor(new Color(102, 102, 102));// 设置颜色
			g.drawString("向你推荐", 150, 520);

			// 首页还有更多精彩
			g.setFont(new Font("微软雅黑", Font.PLAIN, 24));// 设置字体
			g.setColor(new Color(163, 163, 163));// 设置颜色
			g.drawString("首页还有更多精彩~", 150, 570);
			
			ByteArrayInputStream bais = new ByteArrayInputStream(qRCodeBytes);
			logger.debug("转换流结束,bais={}", bais);
			BufferedImage imageCode = readImageIo(bais);
			g.drawImage(imageCode.getScaledInstance(140, 140, Image.SCALE_SMOOTH), 380, 460, null);

			g.setColor(new Color(210, 210, 210));
			g.drawRoundRect(380, 460, 140, 140, 8, 8);
			g.dispose();

			// 上传合成图片至阿里云OSS
			byte[] resultImageBytes = imageToBytes(image, "png");
			ByteArrayInputStream resultImageInputStream = new ByteArrayInputStream(resultImageBytes);
			return resultImageInputStream;
		} catch (Exception e) {
			logger.error("getSkuSharePosters", e);
		}
		return null;
	}

	public ByteArrayInputStream getSpuPosters(byte[] qRCodeBytes, Spu spu, PosterAppInfo info, String headImgUrl){
		BufferedImage image = new BufferedImage(info.getPostWidth(), info.getPostHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = image.createGraphics();
		image = g.getDeviceConfiguration().createCompatibleImage(info.getPostWidth(), info.getPostHeight(),
				Transparency.TRANSLUCENT);
		g.dispose();
		g = image.createGraphics();

		g.setColor(new Color(255, 255, 255));
		g.fillRoundRect(0, 0, info.getPostWidth(), info.getPostHeight(), 10, 10);
		g.setColor(new Color(210, 210, 210));
		g.drawRect(20, 20, info.getPostWidth() - 40, info.getPostHeight() - 40);

		// 商品主图
		InputStream frameInputStream = getImageStream(spu.getMainImg());
		BufferedImage imageFrame = readImageIo(frameInputStream);
		g.drawImage(imageFrame.getScaledInstance(498, 300, Image.SCALE_SMOOTH), 30, 30, null);

		// 标题
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
		g.setFont(new Font("微软雅黑", Font.BOLD, 28));// 设置字体
		g.setColor(new Color(51, 51, 51));// 设置颜色
		String title = spu.getTitle();
		if (title.length() > 15)
			title = title.substring(0, 15) + "......";
		g.drawString(title, 50, 400);

		// 原价
		g.setFont(new Font("微软雅黑", Font.BOLD, 24));// 设置字体
		g.setColor(new Color(252, 67, 42));// 设置颜色
		g.drawString("¥ " + spu.getMinPrice(), 50, 440);

		// 最低价格
		g.setColor(new Color(163, 163, 163));// 设置颜色
		AttributedString as = new AttributedString("¥ " + spu.getPrice());
		as.addAttribute(TextAttribute.FONT, new Font("微软细黑", Font.PLAIN, 24));
		as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
		g.drawString(as.getIterator(), 180, 440);

		// 微信图像
		if (StringUtils.isBlank(headImgUrl) || headImgUrl.equals("undefined")) {
			headImgUrl = APP_DEFAULT_HEADIMG;
		}
		InputStream inputStreamHead = getImageStream(headImgUrl);
		BufferedImage bufferedImageHead = readImageIo(inputStreamHead);
		BufferedImage circleBufferedImage = roundImage(bufferedImageHead, bufferedImageHead.getWidth(),
				bufferedImageHead.getWidth());
		g.drawImage(circleBufferedImage.getScaledInstance(90, 90, Image.SCALE_SMOOTH), 50, 490, null);

		// 向你推荐
		g.setFont(new Font("微软雅黑", Font.PLAIN, 28));// 设置字体
		g.setColor(new Color(102, 102, 102));// 设置颜色
		g.drawString("向你推荐", 150, 520);

		// 首页还有更多精彩
		g.setFont(new Font("微软雅黑", Font.PLAIN, 24));// 设置字体
		g.setColor(new Color(163, 163, 163));// 设置颜色
		g.drawString("首页还有更多精彩~", 150, 560);

		BufferedImage imageCode = readImageIo(new ByteArrayInputStream(qRCodeBytes));
		g.drawImage(imageCode.getScaledInstance(140, 140, Image.SCALE_SMOOTH), 380, 460, null);

		g.setColor(new Color(210, 210, 210));
		g.drawRoundRect(380, 460, 140, 140, 8, 8);
		g.dispose();

		// 上传合成图片至阿里云OSS
		byte[] resultImageBytes = imageToBytes(image, "png");
		ByteArrayInputStream resultImageInputStream = new ByteArrayInputStream(resultImageBytes);
		return resultImageInputStream;
	}

	// 生成悦店海报
	public ByteArrayInputStream getYueDianPosters(byte[] qRCodeBytes, Merchant merchant,
												  com.dragon.modules.yuegou.model.merchant.PosterAppInfo info, String headImgUrl){
		BufferedImage image = new BufferedImage(info.getPostWidth(), info.getPostHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = image.createGraphics();
		image = g.getDeviceConfiguration().createCompatibleImage(info.getPostWidth(), info.getPostHeight(),
				Transparency.TRANSLUCENT);
		g.dispose();
		g = image.createGraphics();

		g.setColor(new Color(255, 255, 255));
		g.fillRoundRect(0, 0, info.getPostWidth(), info.getPostHeight(), 10, 10);
		g.setColor(new Color(210, 210, 210));
		g.drawRect(20, 20, info.getPostWidth() - 40, info.getPostHeight() - 40);

		// 悦店LOGO
		InputStream frameInputStream = getImageStream(merchant.getMerchantLogo() == null
				? "http://zzyzx.oss-cn-shenzhen.aliyuncs.com/crm-web/1531306673889.jpg" : merchant.getMerchantLogo());
		BufferedImage imageFrame = readImageIo(frameInputStream);
		g.drawImage(imageFrame.getScaledInstance(160, 160, Image.SCALE_SMOOTH), 80, 100, null);

		// 微信图像
		if (StringUtils.isBlank(headImgUrl) || headImgUrl.equals("undefined"))
			headImgUrl = APP_DEFAULT_HEADIMG;
		InputStream inputStreamHead = getImageStream(headImgUrl);
		BufferedImage bufferedImageHead = readImageIo(inputStreamHead);
		BufferedImage circleBufferedImage = roundImage(bufferedImageHead, bufferedImageHead.getWidth(),
				bufferedImageHead.getWidth());
		g.drawImage(circleBufferedImage.getScaledInstance(90, 90, Image.SCALE_SMOOTH), 80, 430, null);

		// 悦店名称
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
		g.setFont(new Font("微软雅黑", Font.BOLD, 28));// 设置字体
		g.setColor(new Color(51, 51, 51));// 设置颜色
		String title = merchant.getMerchantName();
		if (title.length() > 15)
			title = title.substring(0, 15) + "......";
		g.drawString(title, 80, 340);

		// 悦店地址
		g.setFont(new Font("微软雅黑", Font.PLAIN, 24));// 设置字体
		g.setColor(new Color(163, 163, 163));// 设置颜色
		g.drawString(merchant.getContactAddress() == null ? "sw" : merchant.getContactAddress(), 100, 370);

		// 向你推荐
		g.setFont(new Font("微软雅黑", Font.PLAIN, 28));// 设置字体
		g.setColor(new Color(102, 102, 102));// 设置颜色
		g.drawString("向你推荐一个悦店~", 200, 450);

		ByteArrayInputStream bais = new ByteArrayInputStream(qRCodeBytes);
		BufferedImage imageCode = readImageIo(bais);
		g.drawImage(imageCode.getScaledInstance(160, 160, Image.SCALE_SMOOTH), 300, 100, null);

		g.dispose();

		// 上传合成图片至阿里云OSS
		byte[] resultImageBytes = imageToBytes(image, "png");
		ByteArrayInputStream resultImageInputStream = new ByteArrayInputStream(resultImageBytes);
		return resultImageInputStream;
	}

	// 生成积分兑换分享海报
	public ByteArrayInputStream integralExchangeposters(byte[] qRCodeBytes, Spu spu, PosterAppInfo info,
			String headImgUrl) throws Exception {
		BufferedImage image = new BufferedImage(info.getPostWidth(), info.getPostHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = image.createGraphics();
		image = g.getDeviceConfiguration().createCompatibleImage(info.getPostWidth(), info.getPostHeight(),
				Transparency.TRANSLUCENT);
		g.dispose();
		g = image.createGraphics();

		g.setColor(new Color(255, 255, 255));
		g.fillRoundRect(0, 0, info.getPostWidth(), info.getPostHeight(), 10, 10);
		g.setColor(new Color(210, 210, 210));
		g.drawRect(20, 20, info.getPostWidth() - 40, info.getPostHeight() - 40);

		// 商品主图
		InputStream frameInputStream = getImageStream(spu.getMainImg());
		BufferedImage imageFrame = readImageIo(frameInputStream);
		g.drawImage(imageFrame.getScaledInstance(498, 300, Image.SCALE_SMOOTH), 30, 30, null);

		// 标题
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
		g.setFont(new Font("微软雅黑", Font.BOLD, 28));// 设置字体
		g.setColor(new Color(51, 51, 51));// 设置颜色
		String title = spu.getTitle();
		if (title.length() > 15)
			title = title.substring(0, 15) + "......";
		g.drawString(title, 50, 400);

		// 积分兑换
		// g.setFont(new Font("微软雅黑", Font.BOLD, 24));// 设置字体
		g.setColor(new Color(252, 67, 42));// 设置颜色
		AttributedString as = new AttributedString(spu.getPoint() + "积分兑换" + "+" + spu.getMinPrice() + "元兑换");
		as.addAttribute(TextAttribute.FONT, new Font("微软雅黑", Font.BOLD, 24));
		g.drawString(as.getIterator(), 50, 440);
		// // 最低价格

		// 微信图像
		if (StringUtils.isBlank(headImgUrl) || headImgUrl.equals("undefined"))
			headImgUrl = APP_DEFAULT_HEADIMG;
		InputStream inputStreamHead = getImageStream(headImgUrl);
		BufferedImage bufferedImageHead = readImageIo(inputStreamHead);
		BufferedImage circleBufferedImage = roundImage(bufferedImageHead, bufferedImageHead.getWidth(),
				bufferedImageHead.getWidth());
		g.drawImage(circleBufferedImage.getScaledInstance(90, 90, Image.SCALE_SMOOTH), 50, 490, null);

		// 向你推荐
		g.setFont(new Font("微软雅黑", Font.PLAIN, 28));// 设置字体
		g.setColor(new Color(102, 102, 102));// 设置颜色
		g.drawString("向你推荐", 150, 520);

		// 首页还有更多精彩
		g.setFont(new Font("微软雅黑", Font.PLAIN, 24));// 设置字体
		g.setColor(new Color(163, 163, 163));// 设置颜色
		g.drawString("首页还有更多精彩~", 150, 560);

		// 二维码图片
		ByteArrayInputStream bais = new ByteArrayInputStream(qRCodeBytes);
		BufferedImage imageCode = readImageIo(bais);
		g.drawImage(imageCode.getScaledInstance(140, 140, Image.SCALE_SMOOTH), 380, 460, null);

		g.setColor(new Color(210, 210, 210));
		g.drawRoundRect(380, 460, 140, 140, 8, 8);
		g.dispose();

		// 上传合成图片至阿里云OSS
		byte[] resultImageBytes = imageToBytes(image, "png");
		ByteArrayInputStream resultImageInputStream = new ByteArrayInputStream(resultImageBytes);
		return resultImageInputStream;
	}

	/**
	 * 获取图片流
	 *
	 * @param url
	 * @return
	 */
	private InputStream getImageStream(String url) {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream inputStream = connection.getInputStream();
				return inputStream;
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(String.format("获取网络图片出现异常，图片路径为:%s", url), e);
		}
		return null;
	}

	/**
	 * 将图片处理成圆形
	 *
	 * @param image
	 * @param targetSize
	 * @param cornerRadius
	 * @return
	 */
	private BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) {
		BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = outputImage.createGraphics();
		g2.setComposite(AlphaComposite.Src);
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setColor(Color.WHITE);
		g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
		g2.setComposite(AlphaComposite.SrcAtop);
		g2.drawImage(image, 0, 0, null);
		g2.dispose();
		return outputImage;
	}

	/**
	 * 图片转byte[]
	 *
	 * @param bImage
	 * @param format
	 * @return
	 */
	public byte[] imageToBytes(BufferedImage bImage, String format) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			ImageIO.write(bImage, format, out);
		} catch (IOException e) {
			logger.error(String.format("图片转byte 异常:%s", e.getMessage()), e);
		}
		return out.toByteArray();
	}
	
	private BufferedImage readImageIo(InputStream frameInputStream) {
		try {
			return ImageIO.read(frameInputStream);
		} catch (Exception e) {
			logger.error("readImageIo", e);
		}
		return null;
	}


}
